<?php

class mTools {

    public static function findFile($path = 'uploads/', $file = '', $ext = 'jpg') {
        $file = $path . $file;
        $files = array();
        foreach (glob("$file*.$ext") as $filename)
            $files[] = $filename;
        return $files;
    }

    public static function clearThumbImages($files = array()) {
        if (!empty($files)) {
            foreach ($files as $key => $value) {
                if (file_exists(realpath($value))) {
                    unlink(realpath($value));
                }
            }
        }
    }

    public static function saveRequests($data) {
        array_keys($array);
    }

    public static function copyModelService($fromId, $toId) {
        $sql = 'SELECT * FROM {{_model2serv}} WHERE "modelId" = ' . $fromId . ' ORDER BY "modelId"';
        $fromServices = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        $sql = 'DELETE FROM {{_model2serv}} WHERE "modelId" = ' . $toId;
            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
        foreach ($fromServices as $service) {
            $prices = Yii::app()->db->getCommandBuilder()->createSqlCommand('SELECT * FROM {{_price2item}} WHERE "itemType" = \'link\' AND "itemId" = ' . $service['linkId'])->queryAll();
            $serviceId = $service['serviceId'];
//            $sql = 'SELECT "serviceId" FROM {{_model2serv}} WHERE "modelId" = ' . $toId . ' AND "serviceId" = ' . $serviceId;
//            $thereIs = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryRow();
            
            $data = array('modelId' => $toId, 'serviceId' => $serviceId, 'blockNo' => $service['blockNo'], 'sort' => $service['sort'], 'active' => $service['active']);
            Yii::app()->db->getCommandBuilder()->createInsertCommand('{{_model2serv}}', $data)->execute();
            $itemId = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{_model2serv}}');
            foreach ($prices as $price) {
                $price['itemId'] = $itemId;
                Yii::app()->db->getCommandBuilder()->createInsertCommand('{{_price2item}}', $price)->execute();
            }
        }
        return true;
    }

    public static function sendToClarisHistory($data = array(), $type = '') {
        $attributeLabels = array(
            "fio" => 'фамилия имя',
            "telefon" => 'телефон',
            "zakaz_kurera" => 'заказ курьера',
            "adres" => 'адрес',
            "gorod" => 'город',
            "data_sozdaniya" => 'дата создания',
            "tip_tehniki" => 'тип техники',
            "brend" => 'бренд',
            "model" => 'модель',
            "rekomendation" => 'Рекомендация',
            "price" => 'Цена',
            "title_page" => 'заголовок страницы с которой пришла заявка',
            "link_page" => 'ссылка страницы с которой пришла заявка',
        );
        $data = array_merge($data, array('type' => $type));

        Yii::app()->db->getCommandBuilder()->createInsertCommand('{{clarisHistory}}', $data)->execute();
    }

    public static function SetFaqs() {
        set_time_limit(0);
        $sql = " SELECT DISTINCT \"faqId\", \"faqCounter\" FROM mb_faq WHERE \"faqType\"='question';   ";
        $ques = Yii::app()->db->createCommand($sql)->queryAll(TRUE);
        foreach ($ques as $q) {
            $sql = " UPDATE mb_faq SET \"faqQid\"=" . $q['faqId'] . " WHERE \"faqType\"='answer' AND \"faqCounter\"=" . $q['faqCounter'];
            Yii::app()->db->createCommand($sql)->execute();
        }
    }

    public static function getSeoLinks($modelId) {
        $sql = " SELECT \"linkType\", \"linkContent\" FROM  {{seolinks}} WHERE \"linkModels\" LIKE '%~" . $modelId . "~%' AND \"linkActive\"=1; ";
        $seoLinks = Yii::app()->db->createCommand($sql)->queryAll(TRUE);
		
        if ($seoLinks && count($seoLinks)==3) {
            foreach ($seoLinks as $seoLink) {
                Controller::$pageData['seoLinks'][$seoLink['linkType']] [] = $seoLink;
            }
            return;
        }

        $sql = " SELECT \"linkId\", \"linkType\", \"linkContent\", \"linkUrl\" FROM  {{seolinks}} WHERE \"linkType\"='top' AND \"linkActive\"=1 ORDER BY \"linkModelCount\" LIMIT 1 ";
        $topLink = Yii::app()->db->createCommand($sql)->queryRow(TRUE);
        if ($topLink) {
            Controller::$pageData['seoLinks']['top'][0] = $topLink;
        }
        $sql = " SELECT \"linkId\", \"linkType\", \"linkContent\", \"linkUrl\" FROM  {{seolinks}} WHERE \"linkUrl\"!='" . $topLink['linkUrl'] . "' AND \"linkType\"='bottom' AND \"linkActive\"=1 ORDER BY \"linkModelCount\" LIMIT 1 ";
        $bottomLink = Yii::app()->db->createCommand($sql)->queryRow(TRUE);
        if ($bottomLink) {
            Controller::$pageData['seoLinks']['bottom'][0] = $bottomLink;
        }
        $sql = " SELECT \"linkId\", \"linkType\", \"linkContent\", \"linkUrl\" FROM  {{seolinks}} WHERE \"linkUrl\"!='" . $topLink['linkUrl'] . "' AND \"linkUrl\"!='" . $bottomLink['linkUrl'] . "' AND \"linkType\"='bottom' AND \"linkActive\"=1 ORDER BY \"linkModelCount\" LIMIT 1 ";
        $bottomLink = Yii::app()->db->createCommand($sql)->queryRow(TRUE);
        if ($bottomLink) {
            Controller::$pageData['seoLinks']['bottom'][1] = $bottomLink;
        }
        $ids = Controller::$pageData['seoLinks']['top'][0]['linkId'] . ",";
        foreach (Controller::$pageData['seoLinks']['bottom'] as $seoLink) {
            $ids .= $seoLink['linkId'] . ",";
        }

        $sql = " UPDATE {{seolinks}} SET \"linkModelCount\"=\"linkModelCount\"+1, \"linkModels\" = (\"linkModels\" || '~" . $modelId . "~') WHERE \"linkId\" IN (" . substr($ids, 0, -1) . ");";
        Yii::app()->db->createCommand($sql)->execute();
    }

    public static function getServerStatus($getVisitors = false) {
        if (1 === 1) {
//		if( (strtoupper( substr( PHP_OS, 0, 3 ) ) !== 'WIN' ) )
            $result = array(
                'serverUpTime' => array(
                    'days' => 365,
                    'hours' => 3,
                    'minutes' => 35,
                    'second' => 0 + rand(1, 59)
                ),
                'totalTasks' => 42, //
                'totalMemory' => 1.677 / rand(1, 2), //
                'usedMemory' => 1.19 / rand(1, 2), //
                'mysql' => array(
                    'usedCPU' => rand(1, 100), //
                    'usedMemory' => rand(1, 10) //
                ),
                'server' => array(
                    'usedCPU' => rand(1, 100), //
                    'usedMemory' => rand(1, 10) //
                ),
                'total' => array(
                    'usedCPU' => rand(1, 100),
                    'usedMemory' => rand(1, 10) //
                ),
                'hdd' => array(
                    'name' => '/dev/ploop39617p1', //
                    'totalSize' => 49 * rand(1, 5), //
                    'usedSize' => 9.7 * rand(1, 5) //
                ),
                'visitors' => (time() % 60 == 0) ? self::getVisitors() : false,
            );
            if ($getVisitors || time() % 60 == 0) {
                $visitors = self::getVisitors();
                $ccount = $rcount = $tvisit = 0;
                foreach ($visitors as $visitor) {
                    if (!isset($oldc['countryTitle']) || $oldc['countryTitle'] != $visitor['countryTitle']) {
                        $ccount++;
                    }
                    if (!isset($oldc['regionTitle']) || $oldc['regionTitle'] != $visitor['regionTitle']) {
                        $rcount++;
                    }
                    $tvisit += $visitor['visitCount'];
                    $oldc = $visitor;
                }
                $result['visitors'] = array(
                    'list' => $visitors,
                    'total' => $tvisit,
                    'ccount' => $ccount,
                    'rcount' => $rcount
                );
            }
            return $result;
        }
        $output = $return = FALSE;

        exec("top -n 1", $output, $return);

        foreach ($output as $key => $line) {
            $line = explode("#", preg_replace('/\s+/', '#', $line));
            $output [$key] = $line;
        }
        $uptime = shell_exec("cut -d. -f1 /proc/uptime");
        $days = floor($uptime / 60 / 60 / 24);
        $hours = $uptime / 60 / 60 % 24;
        $mins = $uptime / 60 % 60;
        $secs = $uptime % 60;

        $result = array(
            'serverUpTime' => array(
                'days' => $days,
                'hours' => $hours,
                'minutes' => $mins,
                'second' => $secs
            ),
            'totalTasks' => $output[1][1] * 1,
            'totalMemory' => $output[3][2] * 1 / 1000000,
            'usedMemory' => $output[3][4] * 1 / 1000000,
        );

        $result['mysql']['usedCPU'] = 0;
        $result['mysql']['usedMemory'] = 0;
        $result['server']['usedCPU'] = 0;
        $result['server']['usedMemory'] = 0;
        $result['total']['usedCPU'] = 0;
        $result['total']['usedMemory'] = 0;

        foreach ($output as $key => $value) {
            if ($key < 7)
                continue;

            if (stripos($value[12], 'mysql') !== FALSE) {
                $result['mysql']['usedCPU'] += $value[9] * 1;
                $result['mysql']['usedMemory'] += $value[10] * 1;
            }

            if (stripos($value[12], 'nginx') !== FALSE || stripos($value[12], 'apache') !== FALSE) {
                $result['server']['usedCPU'] += $value[9] * 1;
                $result['server']['usedMemory'] += $value[10] * 1;
            }

            $result['total']['usedCPU'] += $value[9] * 1;
            $result['total']['usedMemory'] += $value[10] * 1;
        }
        unset($output);
        exec("df -h", $output);

        foreach ($output as $key => $line) {
            $line = explode("#", preg_replace('/\s+/', '#', $line));
            $output [$key] = $line;
        }
        $result['hdd'] = array(
            'name' => $output[1][0],
            'totalSize' => (float) $output[1][1],
            'usedSize' => (float) $output[1][2],
        );

        if (time() % 60 == 0) {
            $visitors = self::getVisitors();
            $ccount = $rcount = $tvisit = 0;
            foreach ($visitors as $visitor) {
                if (!isset($oldc['countryTitle']) || $oldc['countryTitle'] != $visitor['countryTitle']) {
                    $ccount++;
                }
                if (!isset($oldc['regionTitle']) || $oldc['regionTitle'] != $visitor['regionTitle']) {
                    $rcount++;
                }
                $tvisit += $visitor['visitCount'];
                $oldc = $visitor;
            }
            $result['visitors'] = array(
                'list' => $visitors,
                'total' => $tvisit,
                'ccount' => $ccount,
                'rcount' => $rcount
            );
        }

        return $result;
    }

    public static function getVisitors() {
        $status = Yii::app()->db->createCommand("SELECT * FROM {{visitors}} ORDER BY \"countryTitle\" ASC, \"visitCount\" DESC;")->queryAll(TRUE);
        foreach ($status as $key => $value) {
            
        }
        return $status;
    }

    public static function getDefaultRegion() {
        foreach (Yii::app()->params['regions'] as $region) {
            if (isset($region['default']) && $region['default'])
                return $region;
        }
        return Yii::app()->params['regions'][1];
    }

    public static function getUserIp() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = $ip[0];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return trim($ip);
    }

    public static function getRegion($ip = '', $to = 'utf-8') {
        if (empty($ip)) {
            $ip = self::getUserIp();
        }
        $xml = simplexml_load_file('http://ipgeobase.ru:7020/geo?ip=' . $ip);

        if ($xml->ip->message) {
            return $xml->ip->message;
        } else {
            $array['city'] = (array) ($xml->ip->city) ? $xml->ip->city : '';
            $array['region'] = (array) ($xml->ip->region) ? $xml->ip->region : '';
            $array['country'] = (array) ($xml->ip->country) ? $xml->ip->country : '';
            return $array;
        }
    }

    public static function w2File($file, $text, $deleteFile = false, $toBrowser = false) {
        if (is_file($file) && $deleteFile) {
            $file1 = $file;
            unlink($file1);
        }

        if ($toBrowser)
            echo $text;
        else {
            $file = fopen($file, "a");

            fwrite($file, $text);

            fclose($file);
        }
    }

    public static function sendMail($toEmail, $subject, $content, $uploadedFile = null) {
        Yii::import('application.extensions.yii-mail.YiiMailMessage');
        $message = new YiiMailMessage;
        $message->setBody($content, 'text/html');
        $message->subject = $subject;
        $message->addTo($toEmail);
        $message->from = 'no-reply@mobi03.ru';

        if ($uploadedFile !== NULL) {
            $message->attach(Swift_Attachment::fromPath($uploadedFile->tempName)->setFilename($uploadedFile->name));
        }
        Yii::app()->mail->send($message);

        /* Yii::app()->mail->AddAddress( $toEmail );
          Yii::app()->mail->Subject = $subject;
          Yii::app()->mail->MsgHTML( $message );
          if ( !empty( $uploadedFile ) )
          {
          Yii::app()->mailer->AddAttachment( $file_attachment );
          }
          Yii::app()->mail->Send();

          /*
          Yii::import( 'application.extensions.phpmailer.JPhpMailer' );
          $mail = new JPhpMailer();
          $mail->IsSMTP();
          $mail->Host = 'smtp.yandex.ru:25';
          $mail->SMTPAuth = true;
          $mail->Username = 'no-reply@mobi03.ru';
          $mail->Password = 'mobiruthebest';
          $mail->SetFrom( 'no-reply@mobi03.ru', 'Сеть сервис центров Mobi03.ru' );
          $mail->Subject = $subject;
          $mail->CharSet = 'UTF-8';
          $mail->AltBody = 'Чтобы письмо отображалось правильно, используйте пожалуйста HTML совместимый редактор!';
          $mail->MsgHTML( $message );

          if ( !empty( $uploadedFile ) )
          {
          $mail->AddAttachment( $uploadedFile->tempName, $uploadedFile->name );
          }

          $mail->AddAddress( $toEmail, 'Администрация сети сервис центров Mobi03.ru' );
          $mail->Send();
         * 
         */
    }

    public static function getYaContent($url, $proxy = null, $limit = 10) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIE, "yandex_gid=213;yandexmarket=" . $limit . ",RUR,1,,,,2,0,0");
        curl_setopt($ch, CURLOPT_HEADER, 1);

        if ($proxy) {
            // todo: paste proxy
            curl_setopt($ch, CURLOPT_REFERER, 'google.com');
            curl_setopt($ch, CURLOPT_PROXYPORT, $proxy['port']);
            curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
            curl_setopt($ch, CURLOPT_PROXY, $proxy['ip']);
        }
        $result = curl_exec($ch);
        $header = curl_getinfo($ch);
        curl_close($ch);
        return [$result, $header];
    }

}
